package com.hwy.catering.interceptor;


import cn.hutool.core.bean.BeanUtil;
import com.hwy.catering.dto.UserDto;
import com.hwy.catering.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hwy.catering.utils.ConstantPool.*;

/**
 * RefreshTokenInterceptor拦截器用来进行token的刷新，拦截功能交给LoginInterceptor来做
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    //LoginInterceptor为我们手动创建的对象，不是spring创建的，没有用到依赖注入，所以不能用@Resource导入
    private StringRedisTemplate stringRedisTemplate;

    //手动导入stringRedisTemplate
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的token
        String token = request.getHeader("authorization");
        if(token == null){
            return true;
        }

        //2、基于token获取redis中的用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(TOKEN_KEY  + token);

        //3、判断用户是否存在
        if (userMap.isEmpty()){
            //4、不存在就拦截
            return true;
        }

        //5、把hashmap转化为UserDto
        UserDto userDto = BeanUtil.fillBeanWithMap(userMap,new UserDto(),true);

        //6、存在，保存用户信息的Threadlocal
        UserHolder.saveUser(userDto);

        //7、刷新token有效期
        stringRedisTemplate.expire(TOKEN_KEY + token,TOKEN_KEY_TTL, TimeUnit.MINUTES);
        //8、刷新存放用户token的redis有效期
        Object id = stringRedisTemplate.opsForHash().get(TOKEN_KEY + token, "id");
        stringRedisTemplate.expire(USER_TOKEN_KEY + id ,USER_TOKEN_KEY_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
